package com.wwwc.index.web.servlet;

import java.io.*;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;
import java.text.DecimalFormat;

import javax.servlet.ServletRequestWrapper;
import javax.ejb.*;
import javax.naming.*;
import java.rmi.*;
import javax.rmi.*;

import com.wwwc.util.web.*;
import com.wwwc.index.web.ejb.database.*;

public class ScheduleDUpdate extends ScheduleD {
    public StringBuffer main(HttpServletRequest request, String call_path, String mid, String aid, String user_name, int user_level) {
	String error   = null;
	String fid     = request.getParameter("fid");
	String vid     = request.getParameter("vid");
	String yid     = request.getParameter("yid");
	String bid     = request.getParameter("bid");
	String stid    = request.getParameter("stid");
	String confirm = request.getParameter("caid");

	int  delete_level = 0;
	String broker_name = getBrokerName(bid);

	StringBuffer message = null;
	/**
	 * delete all (1099, detail record, tick change)
	 */

	if(vid != null && vid.equals("0")) {
	    if(confirm != null && confirm.equals("Delete")) {
		error = deleteAllRecords(fid, user_name, yid, bid, false);
		if(error != null && error.startsWith("Are you sure")) {
		    delete_level = 1;
		}
	    }

	    if(confirm != null && confirm.equals("Confirm Delete")) {
		error = deleteAllRecords(fid, user_name, yid, bid, true);
		if(error == null) {
		    message = new StringBuffer("<BR><BR><BR>Your year ["+yid+"]");
		    message.append(" records for ["+broker_name+"] has been deleted.");
		    return message;
		}
	    }

	    return confirmDeleteAllRecords (call_path, mid, aid, user_name, user_level,
					    yid, bid, stid, fid, vid, error, delete_level);
	}

	/**
	 * confirm data and generate detail records
	 */

	if(vid != null && vid.equals("1")) {
	    if(stid != null && stid.equals("0")) {	
		if(confirm != null && confirm.equals("Confirm")) {
		    error = confirmData(user_name, yid, bid, fid, vid, stid);
		    if(error == null) {
			message = new StringBuffer("Your year ["+yid+"] transaction data for ["+broker_name+"]");
			message.append(" has been confirmed.");
			return message;
		    }
		}

		if(confirm != null && confirm.equals("Delete")) {
		    error = delete1099Data(fid, user_name, yid, bid, false);
		    if(error != null && error.startsWith("Are you sure")) {
			delete_level = 1;
		    }
		}

		if(confirm != null && confirm.equals("Confirm Delete")) {
		    if(deleteDetailRecords (fid, user_name, yid, bid, stid)) {
			error = delete1099Data(fid, user_name, yid, bid, true);
		    }
		    else {
			error = "Delete Detail Records Error.";
		    }
		    if(error == null) {
			message = new StringBuffer("<BR><BR><BR>Your year ["+yid+"]");
			message.append(" records for ["+broker_name+"] has been deleted.");
			return message;
		    }
		}

		return confirmTransactionData(call_path, mid, aid, user_name, user_level,
					      yid, bid, stid, fid, vid, error, delete_level);
	    }

	    return viewTransactionDetailRecords(request, call_path, mid, aid, user_name, user_level,
						yid, bid, stid, fid, vid, error, delete_level);
	}

	/**
	 * Confirm Base year 
	 */

	if(vid != null && vid.equals("2")) {
	    if(confirm != null) {
		if(confirm.equals("No") && stid.equals("1")) { // no more data
		    if(!update1099Status(user_name, yid, bid, 2)) {
			error = "Confirm Error. Please try again!";
		    }
		    else {
			message = new StringBuffer("<BR><BR>Based on your confirmation, ");
			message.append("<BR>system will use year ["+(Integer.parseInt(yid)-1)+"] as");
			message.append(" your ["+broker_name+"]<BR> account [BASE YEAR] to processing you data.<BR>");
			message.append(" ANY LONG OR SHORT HOLDING POSITON BEFORE Dec. 31, "+(Integer.parseInt(yid)-1)+"<BR>");
			message.append(" YOU MUST ADD INTO [PRE-YEAR HOLDING] OF YEAR ["+yid+"]<BR>");
			return message;
		    }
		}

		if(confirm.equals("Yes") && stid.equals("1")) { // has more data
		    message = new StringBuffer("<BR><BR>Please click the [Add] link to add all you date");
		    return message;
		}
	    }
	    
	    return confirmBaseYear (call_path, mid, aid, user_name, user_level, yid, bid, stid, fid, vid, error);
	}

	/**
	 * PRE-HOLDING (Add, confirm)
	 */

	if(vid != null && vid.equals("3")) {
	    if(confirm != null) {
		if(confirm.equals("No")) {
		    if(stid.equals("2") || Integer.parseInt(stid)>3) {
			if(!update1099Status(user_name, yid, bid, 3)) {
			    error = "System Error. Please try again!";
			}
			
			if(error == null) {
			    error = addPreYearIntoDetail(user_name, yid, bid, fid, "3");
			}
		    }

		    if(error == null) {
			return (new StringBuffer("<BR><BR>System is ready to process your data."));
		    }
		}
		
		if(confirm.equals("Yes") || confirm.equals("Edit")) {
		    return addPreYearHoldingRecords(request, call_path, mid, aid, user_name, user_level, yid, bid, stid, fid, vid);
		}

		// no base-year so add last year records into detail holding
		if(confirm.equals("Confirm")) {
		    if(!update1099Status(user_name, yid, bid, 3)) {
			error = "System Error. Please try again!";
		    }
		    if(error == null) {
			error = addLastYearHoldingInToDetail(user_name, yid, bid, fid);
		    }
		    if(error == null) {
			return (new StringBuffer("<BR><BR>Your [PER-YEAR HOLDING] has been confirmed."));
		    }
		    update1099Status(user_name, yid, bid, 2);
		    error = "System error. Please try again.";
		}
	    }

	    if(isBaseYear(user_name, bid, yid)) {
		return addAndConfirmPreYearHolding (call_path, mid, aid, user_name, user_level, yid, bid, stid, fid, vid, error);
	    }
	    else {
		return viewAndConfirmPreYearHolding (call_path, mid, aid, user_name, user_level, yid, bid, stid, fid, vid, error);
	    }
	}

	/**
	 * TICK UPDATE
	 */

	if(vid != null && vid.equals("4")) {
	    if(confirm != null && confirm.equals("Confirm")) {
		if(!update1099Status(user_name, yid, bid, 4)) {
		    message = new StringBuffer("System Error. Please try again!");
		}
		else {
		    message = new StringBuffer("<BR><BR><B>Your almost there!</B>");
		}
		return message;
	    }
	   
	    return confirmTickChange(request, call_path, mid, aid, user_name, user_level, yid, bid, stid, fid, vid, error);
	}

	/**
	 * THIS-YEAR HOLDING
	 *
	 * Use Detail records, pre-holding, worthless to generate THIS-YEAR Holding
	 * 
	 */

	if(vid != null && vid.equals("5")) {
	    if(confirm != null && confirm.equals("Confirm")) {
		if(saveThisYearHoldingRecords(user_name, yid, bid, fid)) {
		    if(!update1099Status(user_name, yid, bid, 5)) {
			message = new StringBuffer("System Error. Please try again!");
		    }
		    else {
			message = new StringBuffer("<BR><BR><B>Good job. All your data has been saved and ready for final review.</B>");
		    }
		}
		else {
		    message = new StringBuffer("<BR><BR><B>Save Data Error. Please try again!</B>");
		}
		return message;
	    }
	    return confirmThisHolding(request, call_path, mid, aid, user_name, user_level, yid, bid, stid, fid, vid, error);
	}
	
	/**
	 * Final
	 *
	 * User [Detail records] and [pre-holding] to generate [FINAL RECORDS]
	 */

	if(vid != null && vid.equals("6")) {
	    if(confirm != null && confirm.equals("Confirm")) {
		HttpSession session = request.getSession(true);
		if(saveFinalRecords(fid, yid, bid, user_name, (Vector)session.getAttribute("MatchedBV"),
				    (Vector)session.getAttribute("MatchedSV"))) {
		    session.setAttribute("MatchedBV", null);
		    session.setAttribute("MatchedSV", null);
		    return addFinalSumInfo(call_path, mid, aid, user_name, user_level, fid, yid, bid, stid, vid, error);
		}
		else {
		    error = "Save data error. Please try again.";
		}
	    }
	    
	    if(confirm != null && confirm.equals("Save")) {
		error = saveFinalSumInfo(request, user_name, fid, yid, bid);
		if(error == null) {
		    update1099Status(user_name, yid, bid, 6);
		    return (new StringBuffer("Schedule-D is ready."));
		}
		
		return addFinalSumInfo(call_path, mid, aid, user_name, user_level, fid, yid, bid, stid, vid, error);
	    }

	    return confirmFinal(request, call_path, mid, aid, user_name, user_level, yid, bid, stid, fid, vid, error);
	}

	return null;
    }

    private String saveFinalSumInfo (HttpServletRequest request, String user_name, String fid,  String yid, String bid) {
	String init_value = request.getParameter("init_value");
	String deduction  = request.getParameter("deduction");
	String carry_over = request.getParameter("carry_over");
	String gain_loss  = request.getParameter("gain_loss");
	double balance   = 0.0;
	double net_carry = 0.0;
	double temp = 0.0;

	if(gain_loss == null) {
	    return "??????????????????";
	}

	String last_year_balance = "0";
	String query = null;

	//==================================================================================
	// TABLE TAX_SCHEDULE_D_SUM 
	// FID(*) USER_NAME YEAR BROKER_ID INIT_VALUE GAIN_LOSS BALANCE DEDUCTION CARRY_OVER
	// INT       VARN    INT   INT       DOUBLE     DOUBLE   DOUBLE   DOUBLE    DOUBLE
	//==================================================================================

	if(init_value == null || init_value.length()<1) {
	    init_value = "0";
	}

	if(!MyUserInputCheck.checkMoney(init_value)) {
	    return "Error found at field [INVESTMENT].";
	}

	if(carry_over == null || carry_over.length()<1) {
	    carry_over = "0";
	}

	if(!MyUserInputCheck.checkMoney(carry_over)) {
	    return "Error found at field [CARRY OVER].";
	}

	if(deduction == null || deduction.length()<1) {
	    deduction = "0";
	}

	if(!MyUserInputCheck.checkMoney(deduction)) {
	    return "Error found at field [DEDUCTION].";
	}

	if(isBaseYear(user_name, bid, yid)) {	
	    balance = Double.parseDouble(init_value)+Double.parseDouble(gain_loss);	    
	}
	else {
	    query = "SELECT BALANCE FROM TAX_SCHEDULE_D_SUM WHERE USER_NAME='"+user_name+"'"+
		" AND YEAR="+(Integer.parseInt(yid)-1)+" AND BROKER_ID="+bid+";";
	    try {
		last_year_balance = ejbdb.selectSingleFieldValue(query, "BALANCE");
	    }
	    catch (Exception e) {
		System.out.println("ScheduleDUpdate:saveFinalSumInfo"+e);
		return "System can't find your last year record.";
	    }
	    
	    balance = Double.parseDouble(init_value)+Double.parseDouble(gain_loss)+Double.parseDouble(last_year_balance);
	}

	temp = Double.parseDouble(gain_loss);
	if(temp >0) {
	    net_carry = java.lang.Math.abs(Double.parseDouble(carry_over))-temp;
	    if(net_carry >= 0) {
		net_carry = 0.0;
	    }
	} 
	else {
	    net_carry = java.lang.Math.abs(Double.parseDouble(carry_over))+java.lang.Math.abs(temp)
		-java.lang.Math.abs(Double.parseDouble(deduction));
	    if(net_carry <= 0) {
		net_carry = 0.0;
	    }
	}

	query = "INSERT INTO TAX_SCHEDULE_D_SUM (FID, USER_NAME, YEAR, BROKER_ID, INIT_VALUE, GAIN_LOSS, BALANCE, DEDUCTION,"+
	    " CARRY_OVER)"+
	    "VALUES ("+fid+",'"+user_name+"',"+ yid+","+ bid+","+init_value+","+gain_loss+","+balance+","+
	    deduction+","+net_carry+");";
	try {
	    if (ejbdb == null) {
		ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	    }
	    if(ejbdb.insert(query) < 0) {
		return "Saving data error. Please try again.";
	    }
	}
	catch(Exception e) {
	    System.out.println(e);
	    return "Saving data error. Please try again.";
	}
	return null;
    }

    private StringBuffer addFinalSumInfo (String call_path, String mid, String aid, String user_name, int user_level, 
					  String fid,  String yid, String bid, String stid,String vid, String error) {
	if(yid == null || bid == null || fid == null || vid == null || stid == null) {
	    return null;
	}

	StringBuffer sbf = new StringBuffer();

	try {
	    String this_gain = null;

	    boolean base_year = isBaseYear(user_name, bid, yid);	  
	    if (ejbdb == null) {
		ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	    }

	    this_gain = ejbdb.getScheduleDFinalGain(fid, user_name);
	    
	    sbf.append("<FORM method=post action="+call_path+">");
	    sbf.append("<TABLE width=90% cellSpacing='0' cellPadding=2 border=1>");
	    if(error != null) {
		sbf.append("<TR><TD align=center colspan=7>");
		sbf.append("<img src=/images/star.gif><I>"+error+"</I>");
		sbf.append("</TD></TR>");
	    }

	    if(base_year) {
		sbf.append("<TR>");
		sbf.append("<TD align=center><B>YEAR</B></TD>");
		sbf.append("<TD align=center><B>BROKER</B></TD>");
		sbf.append("<TD align=center><B>INVESTMENT</B></TD>");
		sbf.append("<TD align=center><B>LOSS(CARRIED OVER)</B></TD>");
		sbf.append("<TD align=center><B>GAIN(THIS YEAR)</B></TD>");
		sbf.append("<TD align=center><B>DEDUCTION</B></TD>");
		sbf.append("</TR>");
		sbf.append("<TR>");
		sbf.append("<TD align=center>"+yid+"</TD>");
		sbf.append("<TD align=center>"+getBrokerName(bid)+"</TD>");
		sbf.append("<TD align=center>$<input type=text name=init_value value=0 size=10 maxLength=20 style='font-size:8pt'></TD>");
		sbf.append("<TD align=center>$<input type=text name=carry_over value=0 size=10 maxLength=20 style='font-size:8pt'></TD>");
		sbf.append("<TD align=center>"+td.format(Double.parseDouble(this_gain))+"</TD>");
		sbf.append("<input type=hidden name=gain_loss value="+td.format(Double.parseDouble(this_gain))+">");
		sbf.append("<TD align=center>$<input type=text name=deduction value=0 size=10 maxLength=20 style='font-size:8pt'></TD>");
		sbf.append("</TR>");
	    }
	    else {
		String query = "SELECT CARRY_OVER FROM TAX_SCHEDULE_D_SUM WHERE USER_NAME='"+user_name+"'"+
		    " AND YEAR="+(Integer.parseInt(yid)-1)+" AND BROKER_ID="+bid+";";
		String carried_over = ejbdb.selectSingleFieldValue(query, "CARRY_OVER");
		if(carried_over == null) {
		    carried_over = "0";
		}
		sbf.append("<TR>");
		sbf.append("<TD align=center><B>YEAR</B></TD>");
		sbf.append("<TD align=center><B>BROKER</B></TD>");
		sbf.append("<TD align=center><B>INVESTMENT</B></TD>");
		sbf.append("<TD align=center><B>LOSS(CARRIED OVER)</B></TD>");
		sbf.append("<TD align=center><B>GAIN(THIS YEAR)</B></TD>");
		sbf.append("<TD align=center><B>DEDUCTION</B></TD>");
		sbf.append("</TR>");
		sbf.append("<TR>");
		sbf.append("<TD align=center>"+yid+"</TD>");
		sbf.append("<TD align=center>"+getBrokerName(bid)+"</TD>");
		sbf.append("<TD align=center>$<input type=text name=init_value value=0 size=10 maxLength=20 style='font-size:8pt'></TD>");
		sbf.append("<TD align=center>$"+td.format(Double.parseDouble(carried_over))+"</TD>");
		sbf.append("<input type=hidden name=carry_over value="+carried_over+">");
		sbf.append("<TD align=center>"+td.format(Double.parseDouble(this_gain))+"</TD>");
		sbf.append("<input type=hidden name=gain_loss value="+td.format(Double.parseDouble(this_gain))+">");
		sbf.append("<TD align=center>$<input type=text name=deduction value=0 size=10 maxLength=20 style='font-size:8pt'></TD>");
		sbf.append("</TR>");
	    }

	    sbf.append("<TR><TD align=center colspan=6>");
	    sbf.append("<input type=submit name=caid value='Save' style='font-size:8pt'>");
	    sbf.append("</TD></TR>");
	    sbf.append("</TABLE>");

	    sbf.append("<input type=hidden name=mid value="+mid+">");
	    sbf.append("<input type=hidden name=aid value="+aid+">");
	    sbf.append("<input type=hidden name=fid value="+fid+">");
	    sbf.append("<input type=hidden name=vid value="+vid+">");
	    sbf.append("<input type=hidden name=stid value="+stid+">");
	    sbf.append("<input type=hidden name=bid value="+bid+">");
	    sbf.append("<input type=hidden name=yid value="+yid+">");
	    sbf.append("</FORM>");
	    sbf.append("<BR><BR>");
	}
	catch (Exception e) {
	    System.out.println("ScheduleD:addSumInfo:"+e);
	}
	return sbf;
    }

    private boolean saveFinalRecords(String fid, String yid, String bid, String user_name, Vector vb, Vector vs) {
	StockRecord rb = null;
	StockRecord rs = null;
	
	if(fid == null || yid == null || bid == null || user_name == null || vb == null || vs == null || vb.isEmpty() || vs.isEmpty()) {
	    System.out.println("ScheduleDUpdate:saveFinaleRecords:Error:101");
	    return false;
	}
	
	vb.trimToSize();
	vs.trimToSize();

	if(vb.size() != vs.size()) {
	    System.out.println("ScheduleDUpdate:saveFinaleRecords:Error:102:vb.size != vs.size");
	    return false;
	}

	Vector vmbr = null;
	Vector vmsr = null;
	String company  = null; //user tike right now (can be replaced if got company name in tick table)
	String tick_b   = null;
	String tick_s   = null;
	int share_b = 0;
	int share_s = 0;
	String gain_loss = null;
	Vector vv = new Vector();  
	Vector v  = null;
	try {
	    for (int n =0; n< vb.size(); n++) {
		vmbr = (Vector)vb.elementAt(n);
		vmsr = (Vector)vs.elementAt(n);
		if(vmbr == null || vmsr == null || vmbr.isEmpty() || vmsr.isEmpty()) {
		    System.out.println("ScheduleDUpdate:saveFinaleRecords:Error:201");
		    return false;
		}
		vmbr.trimToSize();
		vmsr.trimToSize();
		
		if(vmbr.size() != vmsr.size()) {
		    System.out.println("ScheduleDUpdate:saveFinaleRecords:Error:202:vmbr.size != vmsr.size");
		    return false;
		}

		for (int m =0; m< vmbr.size(); m++) {
		    rb = (StockRecord)vmbr.elementAt(m);
		    rs = (StockRecord)vmsr.elementAt(m);
		    tick_b = rb.getTick();
		    tick_s = rs.getTick();
		    share_b = rb.getShare();
		    share_s = rs.getShare();
		    if(!tick_b.equals(tick_s)) {
			System.out.println("ScheduleDUpdate:saveFinaleRecords:Error:301:tick_s != tick_b");
			return false;
		    }
		    if(share_b != share_s) {
			System.out.println("ScheduleDUpdate:saveFinaleRecords:Error:302:share_s != share_b");
			return false;
		    }
		    company = rb.getTick();
		    gain_loss = td.format(java.lang.Math.abs(rs.getCost())-java.lang.Math.abs(rb.getCost()));
		    v = new Vector();
		    v.add(company);
		    v.add(rb.getTick());
		    v.add(""+rb.getShare());
		    v.add(rb.getDate());
		    v.add(td.format(rb.getCost()));
		    v.add(rs.getDate());
		    v.add(td.format(rs.getCost()));
		    v.add(gain_loss);
		    vv.add(v);
		}
	    }

	    if (ejbdb == null) {
		ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	    }
	    
	    if(ejbdb.saveFinalRecords(fid, user_name, yid, bid, vv)) {
		//it will do clean befor save final records
		return true;
	    }
	    return false;
	}
	catch(Exception e) {
	    System.out.println("ScheduleDUpdate:saveFinalRecords:Error:"+e);
	    return false;
	}
    }

    private StringBuffer confirmFinal (HttpServletRequest request, String call_path, String mid, String aid, 
				       String user_name,  int user_level, String yid, String bid, String stid, 
				       String fid, String vid, String error) {
	if(yid == null || bid == null || stid == null || fid == null || vid == null) {
	    return null;
	}

	HttpSession session = request.getSession(true);
	StringBuffer sbf = new StringBuffer();

	Vector vb  = null;
	Vector vs  = null;
	Vector vhb = null;
	Vector vhs = null;
	Vector vmb = null;
	Vector vms = null;

	Vector vvmb = new Vector();
	Vector vvms = new Vector();

	ArrayList atick = null;
	Iterator it = null;
	String tick = null;

	//double tb = 0.0;
	//double ts = 0.0;

	try {
	    boolean base_year = isBaseYear(user_name, bid, yid);	  
	    if (ejbdb == null) {
		ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	    }

	    atick = (ArrayList)ejbdb.selectScheduleDTicks(fid, 1);
	    it = atick.iterator();
	    StockRecordOpration sro = new StockRecordOpration();
	    
	    sbf.append("<FORM method=post action="+call_path+">");

	    sbf.append("<TABLE width=90% cellSpacing='0' cellPadding=2 border=1>");
	    sbf.append("<TR><TD align=center colspan=8>");
	    sbf.append("<input type=submit name=caid value='Confirm' style='font-size:8pt'>");
	    sbf.append("</TD></TR>");
	    if(error != null) {
		sbf.append("<TR><TD align=center colspan=8>");
		sbf.append("<img src=/images/star.gif><I>"+error+"</I>");
		sbf.append("</TD></TR>");
	    }
	    sbf.append("<TR><TD align=center colspan=4><B>BOUGHT</B></TD>");
	    sbf.append("<TD align=center colspan=4><B>SOLD</B></TD></TR>");
	    sbf.append("<TR>");
	    sbf.append("<TD align=center>COST</TD>");
	    sbf.append("<TD align=center>SHARES</TD>");
	    sbf.append("<TD align=center>PRICE</TD>");
	    sbf.append("<TD align=center>DATE</TD>");
	    sbf.append("<TD align=center>COST</TD>");
	    sbf.append("<TD align=center>SHARES</TD>");
	    sbf.append("<TD align=center>PRICE</TD>");
	    sbf.append("<TD align=center>DATE</TD>");
	    sbf.append("</TR>");

	    while(it.hasNext()) {
		tick = (String)it.next();
		vb = ejbdb.selectScheduleDDetailRecordVector(fid, 3, tick, "B"); //order by DATE DESC 3
		vs = ejbdb.selectScheduleDDetailRecordVector(fid, 3, tick, "S"); //order by DATE DESC 3
		sro.setRecordVector(vb, vs);

		vmb = sro.getMatchedBRecordVector();
		vms = sro.getMatchedSRecordVector();
		vhb = sro.getHoldingLongRecordVector();
		vhs = sro.getHoldingShortRecordVector();

		if(vmb != null && !vmb.isEmpty()) {
		    vvmb.add(vmb);
		}
		if(vms != null && !vms.isEmpty()) {
		    vvms.add(vms);
		}
		sbf.append(finalViewRecordSumary(tick, vmb, vms, vhb, vhs));
	    }

	    sbf.append("<TR><TD align=center colspan=8>");
	    sbf.append("<input type=submit name=caid value='Confirm' style='font-size:8pt'>");
	    sbf.append("</TD></TR>");
	    sbf.append("</TABLE>");

	    session.setAttribute("MatchedBV", vvmb);
	    session.setAttribute("MatchedSV", vvms);

	    sbf.append("<input type=hidden name=mid value="+mid+">");
	    sbf.append("<input type=hidden name=aid value="+aid+">");
	    sbf.append("<input type=hidden name=fid value="+fid+">");
	    sbf.append("<input type=hidden name=vid value="+vid+">");
	    sbf.append("<input type=hidden name=stid value="+stid+">");
	    sbf.append("<input type=hidden name=bid value="+bid+">");
	    sbf.append("<input type=hidden name=yid value="+yid+">");
	    sbf.append("</FORM>");
	    sbf.append("<BR><BR>");
	    return sbf;
	}
	catch (Exception e) {
	    System.out.println("ScheduleD:confirmFinal:"+e);
	    return null;
	}
    }

    private StringBuffer confirmTickChange (HttpServletRequest request, String call_path, String mid, String aid, 
					    String user_name,  int user_level, String yid, String bid, String stid, 
					    String fid, String vid, String error) {

	if(yid == null || bid == null || stid == null || fid == null || vid == null) {
	    System.out.println("ScheduleDUpdate:confirmTickChange:101");
	    return null;
	}
	
	int stid_int = Integer.parseInt(stid);
	if(stid_int <3) {
	    System.out.println("ScheduleDUpdate:confirmTickChange:102");
	    return null;
	}

	String submit = request.getParameter("tick_changed");
	StringBuffer sbf = new StringBuffer();

	try {
	    if (ejbdb == null) {
		ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	    }

	    ArrayList a = (ArrayList)ejbdb.selectScheduleDTicks(fid, 1); //1: return ArrayList
	    if(a == null) {
		return (new StringBuffer("<BR>System can't find any tick."));
	    }

	    String otick   = null;
	    String ntick   = null;

	    if(submit != null && submit.equals("Update")) {
		otick = request.getParameter("otick");
		ntick = request.getParameter("ntick");
		
		if(otick == null || otick.length()<1 || otick.startsWith("---")) {
		    error = "Please select [Current Tick].";
		}
		
		if(error == null && (ntick == null || ntick.length()<1)) {
		    error = "Please enter a new value for ["+otick+"].";
		}

		if(error == null) {
		    if(a.indexOf(ntick)==-1) {
			error = "System do not think you need update tick ["+otick+"] to ["+ntick+"].";
		    }
		    else {
			if(ejbdb.updateScheduleDTick(fid, otick, ntick.toUpperCase())<0) {
			    error = "Update error!";
			}
			else {
			    a = (ArrayList)ejbdb.selectScheduleDTicks(fid, 1); //1: return ArrayList
			    otick = null;
			    ntick = null;
			}
		    }
		}
	    }
	    
	    if(a != null) {
		sbf.append("<BR>");
		sbf.append("<FORM method=post action="+call_path+">");
		sbf.append("<TABLE width=90% border=1>");
		sbf.append("<TR><TD align=center>");
		sbf.append("<H3>Tick Update</H3>");
		sbf.append("</TD></TR>");
		sbf.append("<TR><TD  align=center><B>YEAR ["+yid+"] BROKER ["+getBrokerName(bid)+"]</TD></TR>");
		sbf.append("<TR><TD align=center>");
		sbf.append(MyHtmlDisplay.arrayListToTable(a, 8));
		sbf.append("</TD></TR>");

		sbf.append("<TR><TD align=center>Make sure you know what your doing!!</TD></TR>");

		if(error != null) {
		    sbf.append("<TR><TD  align=center><img src=/images/star.gif><I>"+error+"</I></TD></TR>");
		}		    

		sbf.append("<TR><TD align=center>");
		sbf.append("<table cellSpacing='2' cellPadding='2' border='0'><tr>");
		sbf.append("<td><B>Current Tick:</B></td>");
		sbf.append("<td>"+MyHtmlForm.getSelect("otick", a, otick)+"</td>");
		sbf.append("<td><B>New Tick:</B></td>");
		sbf.append("<td><input type=text name=ntick size=10 maxLenght=10></td>");
		sbf.append("<td><input type=submit name=tick_changed value='Update' style='font-size:8pt'></td>");
		sbf.append("</tr></table>");
		sbf.append("</TD></TR>");
		sbf.append("<TR><TD align=center>");
		sbf.append("<BR><input type=submit name=caid value='Confirm' style='font-size:8pt'>");
		sbf.append("</TD></TR>");
			
		sbf.append("</TABLE>");
		sbf.append("<input type=hidden name=mid value="+mid+">");
		sbf.append("<input type=hidden name=aid value="+aid+">");
		sbf.append("<input type=hidden name=fid value="+fid+">");
		sbf.append("<input type=hidden name=vid value="+vid+">");
		sbf.append("<input type=hidden name=stid value="+stid+">");
		sbf.append("<input type=hidden name=bid value="+bid+">");
		sbf.append("<input type=hidden name=yid value="+yid+">");
		sbf.append("</FORM>");
	    }
	}
	catch (Exception e) {
	    System.out.println("ScheduleD:confirmThisHolding:401"+e);
	}
	return sbf;
    }

    private  StringBuffer displayThisYearHoldingStockRecordVector(String broker, String year, Vector vr, Vector vwt, String error) {
	StringBuffer sbf = new StringBuffer();
	sbf.append("<TABLE width=90% border=1>");
	sbf.append("<TR><TD align=center colspan=7>");
	sbf.append("<H3>YEAR ["+year+"] BROKER ["+getBrokerName(broker)+"] HOLDING RECORDS</H3>");
	sbf.append("</TD>");
	sbf.append("</TR>");
	if(error != null) {
	    sbf.append("<TR><TD align=center colspan=7>");
	    sbf.append("<img src=/images/star.gif>"+error);
	    sbf.append("</TD>");
	    sbf.append("</TR>");
	}
	sbf.append("<TR><TD align=center>BOUGHT/SOLD</TD><TD align=center>COST</TD>");
	sbf.append("<TD align=center>TICK</TD><TD align=center>SHARES</TD>");
	sbf.append("<TD align=center>PRICE</TD><TD align=center>DATE</TD><TD align=center>WORTHLESS</TD></TR>");

	Enumeration enum = vr.elements();
	StockRecord r  = null;
	StringBuffer bsbf = new StringBuffer();

	try {
	    while(enum.hasMoreElements()) {
		r = (StockRecord)enum.nextElement();
		bsbf.append("<TR>");
		bsbf.append("<TD align=center>"+r.getBuySell()+"</TD>");
		bsbf.append("<TD align=right>"+td.format(java.lang.Math.abs(r.getCost()))+"</TD>");
		bsbf.append("<TD align=center>"+r.getTick()+"</TD>");
		bsbf.append("<TD align=right>"+r.getShare()+"</TD>");
		bsbf.append("<TD align=right>"+td.format(r.getPrice())+"</TD>");
		bsbf.append("<TD align=center>"+r.getDate()+"</TD>");

		if(vwt != null && vwt.contains(r.getTick())) {
		    bsbf.append("<TD align=center>");
		    bsbf.append("<input type=checkbox checked name=worthless_"+r.getTick()+" value="+r.getTick()+"></TD>");
		}
		else {
		    bsbf.append("<TD align=center><input type=checkbox name=worthless_"+r.getTick()+" value="+r.getTick()+"></TD>");
		}
		bsbf.append("</TR>");
	    }
	}
	catch (Exception e) {
	    System.out.println("ScheduleD:displayStockRecords:Error:401:"+e);
	    bsbf = new StringBuffer("Loading Data Error.");
	}
	if(bsbf != null) {
	    sbf.append(bsbf);
	}
	sbf.append("</TABLE>");
	return sbf;
    }

    private StringBuffer confirmThisHolding (HttpServletRequest request, String call_path, String mid, String aid, 
					     String user_name,  int user_level, String yid, String bid, String stid, 
					     String fid, String vid, String error) {
	/**
	 *  this method is to confirm generated this year holding records
	 *  after confirm, this year holding records will be save into 
	 *  TAX_SCHEDULE_D_HOLDING table
	 */

	if(yid == null || bid == null || stid == null || fid == null || vid == null) {
	    return null;
	}
	
	int stid_int = Integer.parseInt(stid);

	StringBuffer sbf = null;

	try {
	    if (ejbdb == null) {
		ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	    }

	    Vector vv    = null;
	    Vector vvh   = null;
	    int order = 0;  //[0: DATE] [1: BS] [2: TICK]
	    
	    // vv should includ this year detail records and pre-year holding records
	    // since pre-year holding records have been added after confirmed pre-year
	    // holding with status == 3 in detail records

	    vv = ejbdb.selectScheduleDDetailRecordVector(fid,0); 
	    vvh = getHoldingRecordVector(fid, user_name, yid, bid, vv);

	    Vector vwt   = null;
	    String submit = request.getParameter("caid");
	    StringBuffer esbf = new StringBuffer();
	    if(submit != null && submit.equals("Update")) {
		Enumeration enum = request.getParameterNames();
		String temp = null;
		String value = null;
		vwt = new Vector();
		while(enum.hasMoreElements()) {
		    temp = (String)enum.nextElement();
		    if(temp != null && temp.startsWith("worthless_")) {
			value = request.getParameter(temp);
			if(value != null && value.length()>0) {
			    vwt.add(value);
			    esbf.append("Make "+value+" as worthless? <BR>");
			}
		    }
		}
		
		temp = null;
		value = null;
		
		if(vwt.isEmpty()) {
		    vwt = null;
		    esbf = null;
		}
	    }

	    if(submit != null && submit.equals("Confirm Update")) {
		Enumeration enum = request.getParameterNames();
		String temp = null;
		String value = null;
		vwt = new Vector();
		while(enum.hasMoreElements()) {
		    temp = (String)enum.nextElement();
		    if(temp != null && temp.startsWith("worthless_")) {
			value = request.getParameter(temp);
			if(value != null && value.length()>0) {
			    vwt.add(value);
			}
		    }
		}
		
		temp = null;
		value = null;
		
		if(vwt.isEmpty()) {
		    vwt = null;
		    esbf = null;
		}
		else {
		    Vector vvw = new Vector();
		    Vector vw = null;
		    enum = vvh.elements();
		    StockRecord r  = null;
		    String bs = null;
		    try {
			while(enum.hasMoreElements()) {
			    vw = new Vector();
			    r = (StockRecord)enum.nextElement();
			    if(vwt.contains(r.getTick())) {
				if((r.getBuySell()).equals("B")) {
				    bs = "S";
				}
				else {
				    error = "Processing data error. You are making Short position as worthless??";
				    break;
				}
				vw.add(bs);
				vw.add("0.0");
				vw.add(r.getTick());
				vw.add(""+r.getShare());
				vw.add("0.0");
				vw.add(yid+"-12-31");
				vvw.add(vw);
			    }
			}
		       
			if(ejbdb.insertScheduleDDetailRecords(Integer.parseInt(fid), user_name, Integer.parseInt(yid),
							      Integer.parseInt(bid), 4, vvw) <0) {
			    error = "Save data error. Please try again.";
			}
			else {
    
			    vv = ejbdb.selectScheduleDDetailRecordVector(fid,0); 
			    vvh = getHoldingRecordVector(fid, user_name, yid, bid, vv);

			    vw = null;
			    vvw = null;
			    vwt = null;
			    esbf = null;
			    r = null;
			}
		    }
		    catch(Exception e) {
			error = "Update Error. Please try again.";
		    }
		}
	    }
		
	    sbf = new StringBuffer();
	    sbf.append("<FORM method=post action="+call_path+">");
	    
	    if(vwt != null && esbf != null) {
		error = "This change  will afect your final GAIN/LOSS :<BR>"+esbf.toString();
	    }
	    sbf.append(displayThisYearHoldingStockRecordVector(bid, yid, vvh, vwt, error));
	    
	    sbf.append("<TABLE width=90% border=0>");
	    sbf.append("<TR><TD align=center>");
	    if(submit != null && submit.equals("Update") && vwt != null) {
		sbf.append("<input type=submit name=caid value='Confirm Update' style='font-size:8pt'>");
		sbf.append("<input type=submit name=caid value='Cancel' style='font-size:8pt'>");
	    }
	    else {
		sbf.append("<input type=submit name=caid value='Update' style='font-size:8pt'>");
	    }
	    sbf.append("<input type=submit name=caid value='Confirm' style='font-size:8pt'>");
	    sbf.append("</TD></TR>");
	    sbf.append("</TABLE>");
	    sbf.append("<input type=hidden name=mid value="+mid+">");
	    sbf.append("<input type=hidden name=aid value="+aid+">");
	    sbf.append("<input type=hidden name=fid value="+fid+">");
	    sbf.append("<input type=hidden name=vid value="+vid+">");
	    sbf.append("<input type=hidden name=stid value="+stid+">");
	    sbf.append("<input type=hidden name=bid value="+bid+">");
	    sbf.append("<input type=hidden name=yid value="+yid+">");
	    sbf.append("</FORM>");
	    sbf.append("<BR><BR>");
	    return sbf;
	}
	catch (Exception e) {
	    System.out.println("ScheduleD:confirmThisHolding:"+e);
	    return null;
	}
    }

    private StringBuffer confirmDeleteAllRecords (String call_path, String mid, String aid, String user_name, 
						  int user_level, String year, String broker, String status, 
						  String fid, String vid, String error, int delete_level) {

	StringBuffer sbf = new StringBuffer();
	if(year == null || broker == null || status == null || fid == null || vid == null) {
	    return (new StringBuffer("Data not found"));
	}

	sbf.append("<BR>");
	sbf.append("<FORM method=post action="+call_path+">");
	sbf.append("<TABLE width=90% border=1>");
	sbf.append("<TR><TD align=center colspan=6>");
	sbf.append("<B>Delete All Records of YEAR ["+year+"] BROKER ["+getBrokerName(broker)+"]</TD>");
	sbf.append("</TR>");
	if(error != null) {
	    sbf.append("<TR><TD align=center colspan=6><img src=/images/star.gif><I>"+error+"</I></TD></TR>");
	}

	sbf.append("<TR><TD align=center colspan=6>");
	if(delete_level == 0 && error == null) {
	    sbf.append("<input type=submit name=caid value=Delete style='font-size:8pt'>");
	}
	if(delete_level == 1) {
	    sbf.append("<input type=submit name=caid value='Confirm Delete' style='font-size:8pt'>");
	}

	sbf.append("<input type=hidden name=mid value="+mid+">");
	sbf.append("<input type=hidden name=aid value="+aid+">");
	sbf.append("<input type=hidden name=fid value="+fid+">");
	sbf.append("<input type=hidden name=vid value="+vid+">");
	sbf.append("<input type=hidden name=stid value="+status+">");
	sbf.append("<input type=hidden name=bid value="+broker+">");
	sbf.append("<input type=hidden name=yid value="+year+">");
	sbf.append("</TD></TR>");		
	sbf.append("</TABLE>");
	sbf.append("</FORM>");
	return sbf;
    }

    private StringBuffer confirmTransactionData (String call_path, String mid, String aid, String user_name, 
						 int user_level, String year, String broker, String status, 
						 String fid, String vid, String error, int delete_level) {

	StringBuffer sbf = new StringBuffer();
	if(year == null || broker == null || status == null || fid == null || vid == null) {
	    return (new StringBuffer("Data not found"));
	}

	if(status != null && status.equals("0")) {
	    String field = null;
	    if(vid != null && vid.equals("1")) {
		field = "TRA_DATA";
	    }

	    Vector vv = null; 
	    try {
		if (ejbdb == null) {
		    ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
		}
		vv = ejbdb.selectSingleFieldScheduleDData(Integer.parseInt(fid), user_name, field);
	    }
	    catch (Exception e) {
		System.out.println("ScheduleD:"+e);
		return (new StringBuffer("Loading Data Error."));
	    }

	    if(vv == null || vv.isEmpty()) {
		return new StringBuffer("Data not found.");
	    }

	    Vector v  = null;
	    sbf.append("<BR>");
	    sbf.append("<FORM method=post action="+call_path+">");
	    sbf.append("<TABLE width=90% border=1>");
	    sbf.append("<TR><TD align=center colspan=6>");
	    sbf.append("<B>Transaction Data of YEAR ["+year+"]");
	    sbf.append(" BROKER ["+getBrokerName(broker)+"]</TD>");
	    sbf.append("</TR>");
	    
	    sbf.append("<TR><TD align=center colspan=6>");
	    sbf.append("<input type=submit name=caid value=Confirm style='font-size:8pt'>");
	    
	    if(delete_level == 0) {
		sbf.append("<input type=submit name=caid value=Delete style='font-size:8pt'>");
	    }
	    if(delete_level == 1) {
		sbf.append("<input type=submit name=caid value='Confirm Delete' style='font-size:8pt'>");
	    }

	    sbf.append("<input type=hidden name=mid value="+mid+">");
	    sbf.append("<input type=hidden name=aid value="+aid+">");
	    sbf.append("<input type=hidden name=fid value="+fid+">");
	    sbf.append("<input type=hidden name=vid value="+vid+">");
	    sbf.append("<input type=hidden name=stid value="+status+">");
	    sbf.append("<input type=hidden name=bid value="+broker+">");
	    sbf.append("<input type=hidden name=yid value="+year+">");
	    sbf.append("</TD></TR>");		

	    if(error != null) {
		sbf.append("<TR><TD align=center colspan=6><img src=/images/star.gif><I>"+error+"</I></TD></TR>");
	    }
	    
	    sbf.append("<TR><TD align=center>BOUGHT/SOLD</TD><TD align=center>COST</TD>");
	    sbf.append("<TD align=center>TICK</TD><TD align=center>SHARES</TD>");
	    sbf.append("<TD align=center>PRICE</TD><TD align=center>DATE</TD></TR>");
	    
	    Enumeration enum1 = vv.elements();
	    Enumeration enum2 = null;
	    int n =0;
	    String bs    = null;
	    double cost  = 0.0;
	    String tick  = null;
	    int share    = 0;
	    double price = 0.0;
	    String date  = null;
	    
	    try {
		while(enum1.hasMoreElements()) {
		    v = (Vector)enum1.nextElement();
		    enum2 = v.elements();
		    
		    sbf.append("<TR>");

		    while(enum2.hasMoreElements()) {
			bs    = (String)enum2.nextElement();
			cost  = Double.parseDouble(""+enum2.nextElement());
			tick  = (String)enum2.nextElement();
			share = (new Double(""+enum2.nextElement())).intValue();
			price = Double.parseDouble(""+enum2.nextElement());
			date  = (String)enum2.nextElement();

			sbf.append("<TD align=center>"+bs+"</TD>");
			sbf.append("<TD align=right>"+cost+"</TD>");
			sbf.append("<TD align=center>"+tick+"</TD>");
			sbf.append("<TD align=right>"+share+"</TD>");
			sbf.append("<TD align=right>"+price+"</TD>");
			sbf.append("<TD align=center>"+date+"</TD>");
		    }
		    
		    sbf.append("</TR>");
		}
	    }
	    catch (Exception e) {
		System.out.println("viewAndUpdate1099DataField:Error:100:"+e);
		return (new StringBuffer("Processing Data Error!"));
	    }

	    sbf.append("</TABLE>");
	    sbf.append("</FORM>");
	   
	    enum1 = null;
	    enum2 = null;
	    vv = null;
	    v  = null;
	}
	return sbf;
    }

  
    private StringBuffer confirmBaseYear (String call_path, String mid, String aid, String user_name, 
					      int user_level, String year, String broker, String status, 
					      String fid, String vid, String error) {
	
	StringBuffer sbf = new StringBuffer();
	if(error != null) {
	    sbf.append("<img src=/images/star.gif><I>"+error+"</I>");
	}

	if(status != null && status.equals("1")) {
	    sbf.append("<BR>");
	    sbf.append("<FORM method=post action="+call_path+">");
	    sbf.append("<TABLE width=90% border=0>");		
	    sbf.append("<TR><TD align=center>");
	    sbf.append("IF YOUR HAVE ANY TRANSACTION DATA FILE FOR YOUR ["+getBrokerName(broker)+"]");
	    sbf.append(" ACCOUNT<BR><B>BEFORE</B> YEAR ["+year+"], PLEASE ADD IT NOW.<BR><BR>");
	    sbf.append("<BR><img src=/images/star.gif>!!! STOP !!!<img src=/images/star.gif><BR><BR>");
	    sbf.append("<BR>ONCE YOU CONFIRMED YOUR [BASE-YEAR],");
	    sbf.append("<BR>YOU WILL <B>NOT</B> BE ABLE TO ADD ANY TRANSACTION DATA <B>BEFORE</B> YEAR "+year);
	    sbf.append("</TD></TR>");
	    sbf.append("<TR><TD align=center><BR><BR>");
	    sbf.append("<input type=submit value=Continue   style='font-size:8pt'>");
	    sbf.append("<input type=hidden name=mid value="+mid+">");
	    sbf.append("<input type=hidden name=caid value=No>");
	    sbf.append("<input type=hidden name=aid value="+aid+">");
	    sbf.append("<input type=hidden name=fid value="+fid+">");
	    sbf.append("<input type=hidden name=vid value="+vid+">");
	    sbf.append("<input type=hidden name=stid value="+status+">");
	    sbf.append("<input type=hidden name=bid value="+broker+">");
	    sbf.append("<input type=hidden name=yid value="+year+">");
	    sbf.append("</TD></TR>");		
	    sbf.append("</TABLE>");
	    sbf.append("</FORM>");
	}
	return sbf;
    }

    private String addLastYearHoldingInToDetail(String user_name, String yid, String bid, String fid) {
	// If this year is not base year, PRE-YEAR HOLDING will come form last year Holding
	// Add last year holding into this year detail records

	try {
	    if(ejbdb == null) {
		ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	    }

	    Vector vvh = ejbdb.getLastYearDetailHoldingRecordVector(user_name, yid, bid);
	    
	    if(vvh == null || vvh.isEmpty()) {
		return null;
	    }

	    return insertDetailRecords(user_name, yid, bid, fid, "3", vvh);
	}
	catch (Exception e) {
	    System.out.println(e);
	}
	return null;
    }

    private StringBuffer viewAndConfirmPreYearHolding(String call_path,  String mid, String aid, String user_name, 
						      int user_level, String yid, String bid, String stid, 
						      String fid, String vid, String error) {
	String record_status = "3";
	StringBuffer sbf = new StringBuffer();
	Vector v = null;

	try {
	    if (ejbdb == null) {
		ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	    }
	    v = ejbdb.getLastYearDetailHoldingRecords(user_name, yid, bid);
	}
	catch (Exception e) {
	    System.out.println("ScheduleDViewer:viewDetailRecord:"+e);
	}

	sbf.append("<FORM method=post action="+call_path+">");
	sbf.append("<TABLE width=90% border=1 cellSpacing=0 cellPadding=2>");
	sbf.append("<TR><TD align=center colspan=6><BR><H3>PRE-YEAR ["+yid+"] HOLDING ");
	sbf.append(" BROKER ["+getBrokerName(bid)+"]</H3><BR></TD></TR>");
	sbf.append("</TD></TR>");	

	sbf.append("<TR>");
	sbf.append("<TD align=center>BOUGHT/SOLD</TD>");
	sbf.append("<TD align=center>COST</TD>");
	sbf.append("<TD align=center>TICK</TD>");
	sbf.append("<TD align=center>SHARES</TD>");
	sbf.append("<TD align=center>PRICE</TD>");
	sbf.append("<TD align=center>DATE</TD>");
	sbf.append("<TR>");

	if(error != null) {
	    sbf.append("<TR><TD align=center colspan=6>");
	    sbf.append("<img src=/images/star.gif><I>"+error+"</I>");
	    sbf.append("</TD></TR>");	
	}

	if(v == null || v.isEmpty()) {
	    sbf.append("<TR><TD align=center colspan=6>");
	    sbf.append("YOU DO NOT HAVE ANY POSITION CARRIED OVER FROM YEAR ");
	    sbf.append(Integer.parseInt(yid)+" TO YEAR "+yid+"</TD></TR>");
	    sbf.append("<TR>");
	    sbf.append("<TD align=center colspan=6><input type=submit name=caid value='Confirm' style='font-size: 8pt'>"); 
	    sbf.append("</TD>"); 
	    sbf.append("</TR>");
	    sbf.append("</TABLE>");
	    sbf.append("<input type=hidden name=mid value="+mid+">");
	    sbf.append("<input type=hidden name=aid value="+aid+">");
	    sbf.append("<input type=hidden name=fid value="+fid+">");
	    sbf.append("<input type=hidden name=vid value="+vid+">");
	    sbf.append("<input type=hidden name=stid value="+stid+">");
	    sbf.append("<input type=hidden name=bid value="+bid+">");
	    sbf.append("<input type=hidden name=yid value="+yid+">");
	    sbf.append("</FORM>");
	    return sbf;
	}
	else {
	    sbf.append("<TR>");
	    sbf.append("<TD align=center colspan=6><input type=submit name=caid value='Confirm' style='font-size: 8pt'>"); 
	    sbf.append("</TD>"); 
	    sbf.append("</TR>");
	    sbf.append("<input type=hidden name=mid value="+mid+">");
	    sbf.append("<input type=hidden name=aid value="+aid+">");
	    sbf.append("<input type=hidden name=fid value="+fid+">");
	    sbf.append("<input type=hidden name=vid value="+vid+">");
	    sbf.append("<input type=hidden name=stid value="+stid+">");
	    sbf.append("<input type=hidden name=bid value="+bid+">");
	    sbf.append("<input type=hidden name=yid value="+yid+">");
	    sbf.append("</FORM>");
	}

	Enumeration enum = v.elements();
	String bs    = null;
	double cost  = 0.0;
	String tick  = null;
	int share    = 0;
	double price = 0.0;
	String date  = null;
	
	try {

	    Vector vr = null;
	    Vector vrh = new Vector();
 
	    while(enum.hasMoreElements()) {
		bs    = (String)enum.nextElement();
		cost  = Double.parseDouble(""+enum.nextElement());
		tick  = (String)enum.nextElement();
		share = (new Double(""+enum.nextElement())).intValue();
		price = Double.parseDouble(""+enum.nextElement());
		date  = (String)enum.nextElement();

		sbf.append("<TR>");
		sbf.append("<TD align=center>"+bs+"</TD>");
		sbf.append("<TD align=right>"+td.format(java.lang.Math.abs(cost))+"</TD>");
		sbf.append("<TD align=center>"+tick+"</TD>");
		sbf.append("<TD align=right>"+share+"</TD>");
		sbf.append("<TD align=right>"+td.format(price)+"</TD>");
		sbf.append("<TD align=center>"+date+"</TD>");
		sbf.append("</TR>");
	    }
	}
	catch (Exception e) {
	    System.out.println("viewTransactionDetailRecords:Error:100:"+e);
	}

	sbf.append("</TABLE>");
	enum = null;
	v    = null;
	return sbf;
    }

    private StringBuffer addAndConfirmPreYearHolding (String call_path, String mid, String aid, String user_name, 
						      int user_level, String yid, String bid, String stid, 
						      String fid, String vid, String error) {

	StringBuffer sbf = new StringBuffer();
	if(error != null) {
	    sbf.append("<img src=/images/star.gif><I>"+error+"</I>");
	}

	if(stid != null && stid.equals("2")) {
	    sbf.append(confirmPreYearHoldingMessage(bid, yid));
	    sbf.append("<FORM method=post action="+call_path+">");
	    sbf.append("<TABLE>");
	    sbf.append("<TR>");
	    sbf.append("<TD align=center>");
	    sbf.append("<B>Do you have any [PRE-YEAR HOLDING] position for your ["+getBrokerName(bid)+"] account?</B>"); 
	    sbf.append("</TD>"); 
	    sbf.append("</TR>");
	    sbf.append("<TR>");
	    sbf.append("<TD align=center><BR><BR><input type=submit name=caid value='Yes' style='font-size: 8pt'>"); 
	    sbf.append("&nbsp;&nbsp;<input type=submit value='No' name=caid style='font-size: 8pt'></TD>"); 
	    sbf.append("</TR>");
	    sbf.append("<TR>");
	    sbf.append("<TD align=center>");
	    sbf.append("</TD>"); 
	    sbf.append("</TR>");
	    sbf.append("</TABLE>");
	    sbf.append("<input type=hidden name=mid value="+mid+">");
	    sbf.append("<input type=hidden name=aid value="+aid+">");
	    sbf.append("<input type=hidden name=fid value="+fid+">");
	    sbf.append("<input type=hidden name=vid value="+vid+">");
	    sbf.append("<input type=hidden name=stid value="+stid+">");
	    sbf.append("<input type=hidden name=bid value="+bid+">");
	    sbf.append("<input type=hidden name=yid value="+yid+">");
	    sbf.append("</FORM>");
	}
	return sbf;
    }

    private String confirmData (String user_name, String year, String broker, 
				String fid, String column, String status) {
	if(status == null || user_name == null || year == null || broker == null 
	   || fid == null || column == null) {
	    return "Error";
	}

	String error = null;

	if(status.equals("0")) {
	    if(error == null) {
		if(isBaseYear(user_name, broker, year)) {
		    error = generateDetailRecords (user_name, year, broker, fid, status);
		    if(error == null) {
			if(update1099Status(user_name, year, broker, 1)) {
			    return null;
			}
			else {
			    deleteDetailRecords (fid, user_name, year, broker, status);
			    return "System error! Please try again.";
			}
		    }
		    else {
			return error;
		    }
		}
		else {
		    if(findBaseYear(user_name, broker, year)==-1) {
			return "System can't find your [BADE YEAR]. You have unfinashed records before year ["+year+"].";
		    }
		    else {
			if(findBaseYear(user_name, broker, year) != Integer.parseInt(year)-1) {
			    return "You must finash year ["+(Integer.parseInt(year)-1)+"] Schedule-D first.";
			}
			else {
			    error = generateDetailRecords (user_name, year, broker, fid, status);
			    if(error == null) {
				if(update1099Status(user_name, year, broker, 2)) {
				    return null;
				}
				else {
				    deleteDetailRecords (fid, user_name, year, broker, status);
				    return "System error! Please try again.";
				}
			    }
			    else {
				return error;
			    }
			}
		    }
		}
	    }
	    else {
		return "System Error["+error+"]. Please try again!";
	    }
	}
	return "Confirm level="+status;
    }

    private Vector getHoldingRecordVector(String fid, String user_name, String yid, String bid, Vector vv) {
	Vector vvr = null;
	try {
	    vvr = new Vector ();
	    Vector vht = new Vector(); //hold unmatched ticks

	    ArrayList tka  = (ArrayList)ejbdb.selectScheduleDTicks(fid, 1); //1: ArrayList 2: Hashtable
	    String tick = null;
	    int ushare  = 0;
	    //==================================================================
	    // add tick in vv but not in tka
	    //==================================================================
	    /*
	    Iterator it = tka.iterator();
	    while(it.hasNext()) {
		tick = (String)it.next();
		ushare = ejbdb.scheduleDGetUmatchedShares(fid, user_name, yid, bid, tick);
		if(ushare == 0) {
		    continue;
		}
		vht.add(tick);
	    }
	    */
	    String bs = null;
	    Enumeration enumt = null;
	    Enumeration enum  = null;
	    StockRecord r  = null;
	    StockRecord rh = null;
	    StockRecord rph = null;
	    StockRecord rb  = null;
	    StockRecord rs  = null;
	    Vector v = null;
	    Vector vdown = new Vector();
	    /*
	    enumt = vht.elements();
	    while(enumt.hasMoreElements()) {
		tick = (String)enumt.nextElement();
	    */
	    Iterator it = tka.iterator();
	    while(it.hasNext()) {
		tick = (String)it.next();
		if(vdown.contains(tick)) {
		    continue;
		}
		vdown.add(tick);

		rb = new StockRecord("B", 0.0, tick, 0, 0.0, "0000-00-00");
		rs = new StockRecord("S", 0.0, tick, 0, 0.0, "0000-00-00");

		enum = vv.elements();
		while(enum.hasMoreElements()) {
		    v = (Vector)enum.nextElement();
		    r = new StockRecord(v);
		    if((r.getTick()).equals(tick)) {
			if(r.getBuySell().equals("B")) {
			    rb = addRecords(r, rb);
			}
			if(r.getBuySell().equals("S")) {
			    rs = addRecords(r, rs);
			}
		    }
		}

		rh = subtractRecords(rb, rs);

		if(rh != null) {
		    vvr.add(getHoldingRecord(rh, fid));
		}
	    }
	}
	catch (Exception e) {
	    System.out.println("ScheduleD:getHoldingRecordVector:"+e);
	    return null;
	}
	return vvr;
    }

    private StockRecord getHoldingRecord(StockRecord r, String fid) {
	try {
	    if (ejbdb == null) {
		ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	    }

	    String bs    = null;	
	    String tick  = null;
	    double cost  = 0.0;
	    double price = 0.0;
	    int share    = 0;

	    StockRecord rh  = null;
	    StockRecord rt  = null;
	    StockRecord rm  = null;

	    int cshare = 0;

	    tick = r.getTick();
	    bs = r.getBuySell();
	    share =  r.getShare();
	    Vector vv = ejbdb.selectScheduleDDetailRecordVector(fid, 3, tick, bs);
	    Enumeration enum = vv.elements();
	    Vector v = null;
	    while(enum.hasMoreElements()) {
		v = (Vector)enum.nextElement();
		rt = new StockRecord(v);

		cshare += rt.getShare();
		if(cshare <= share) {
		    if(rh == null) {
			rh = rt;
		    }
		    else {
			rh = addRecords(rh, rt);
		    }
		}

		if(cshare > share) {
		    if(rh == null) {
			rh = splitRecord(rt, share);
		    }
		    else {
			rh = addRecords(rh, splitRecord(rt, (share-rh.getShare())));
		    }
		}
		if(rh != null && rh.getShare() == share) {
		    return rh;
		}
	    }
	}
	catch (Exception e) {
	    System.out.println("ScheduleD:getHoldingRecord:"+e);
	    return null;
	}
	return null;
    }

    private String deleteAllRecords (String fid, String user_name, String year, String broker, boolean delete) {
	String error = null;
	try {
	    if (ejbdb == null) {
		ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	    }

	    //check if any 1099 after current deletion
	    
	    int less_great = 1; 
	    ArrayList alist = ejbdb.selectUserScheduleDInfo (user_name, broker, year, less_great);	    
	    
	    if(alist == null || alist.isEmpty()) {
		if(delete) {
		    String query = 
			"DELETE FROM TAX_SCHEDULE_D         WHERE ID="+fid+" AND USER_NAME='"+user_name+"';"+
			"DELETE FROM TAX_SCHEDULE_D_DETAIL  WHERE FID="+fid+" AND USER_NAME='"+user_name+"';"+
			"DELETE FROM TAX_SCHEDULE_D_TICK    WHERE FID="+fid+" AND USER_NAME='"+user_name+"' AND "+
			"YEAR="+year+" AND BROKER_ID="+broker+";"+
			"DELETE FROM TAX_SCHEDULE_D_HOLDING WHERE FID="+fid+" AND USER_NAME='"+user_name+"' AND "+
			"YEAR="+year+" AND BROKER_ID="+broker+";"+
			"DELETE FROM TAX_SCHEDULE_D_FINAL WHERE FID="+fid+" AND USER_NAME='"+user_name+"' AND "+
			"YEAR="+year+" AND BROKER_ID="+broker+";"+
			"DELETE FROM TAX_SCHEDULE_D_SUM WHERE FID="+fid+" AND USER_NAME='"+user_name+"' AND "+
			"YEAR="+year+" AND BROKER_ID="+broker+";";

		    if(ejbdb.delete(query)<0) { 
			error = "System Error. Please try again.";
		    }
		    else {
			return null;
		    }
		}
		else {
		    error = "Are you sure you want delete year ["+year+"] 1099 data in your ["+getBrokerName(broker)+"] account?";
		}
	    }
	    else {
		error = "System found that you have 1099 data after year ["+year+"] in broker ["+getBrokerName(broker)+"]."+
		    "<BR>Please delete the latest year first!";
	    }
	}
	catch (Exception e) {
	    System.out.println("ScheduleD:delete1099Data:Error:Ejbdb"+e);
	    error = "System Error [101]. Please try again.";
	}
	return error;
    }
   
    private String delete1099Data (String fid, String user_name, String year, String broker, boolean delete) {
	String error = null;
	try {
	    if (ejbdb == null) {
		ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	    }

	    //check if any 1099 after current deletion
	    int less_great = 1; 
	    ArrayList alist = ejbdb.selectUserScheduleDInfo (user_name, broker, year, less_great);	    
	    if(alist == null || alist.isEmpty()) {
		if(delete) {
		    if(1 != ejbdb.delete("DELETE FROM TAX_SCHEDULE_D WHERE ID="+fid+" AND USER_NAME='"+user_name+"';")) {
			error = "System Error. Please try again.";
		    }
		}
		else {
		    error = "Are you sure you want delete year ["+year+"] 1099 data in your ["+getBrokerName(broker)+"] account?";
		}
	    }
	    else {
		error = "System found that you have 1099 data after year ["+year+"] in broker ["+getBrokerName(broker)+"]."+
		    "<BR>Please delete the latest year first!";
	    }
	}
	catch (Exception e) {
	    System.out.println("ScheduleD:delete1099Data:Error:Ejbdb"+e);
	    error = "System Error [101]. Please try again.";
	}
	return error;
    }
   
    private boolean deleteDetailRecords (String fid, String user_name, String year, String broker, String status) {
	return (deleteDetailRecords (fid, user_name, year, broker, Integer.parseInt(status) ));
    }

    private boolean deleteDetailRecords (String fid, String user_name, String year, String broker, int status) {
	try {
	    if (ejbdb == null) {
		ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	    }

	    String query = "DELETE FROM TAX_SCHEDULE_D_DETAIL WHERE USER_NAME='"+
		user_name+"' AND FID="+fid+" AND YEAR="+year+" AND BROKER_ID="+broker+" AND STATUS="+status;

	    if(ejbdb.delete(query)<0) {
		return false;
	    }
	    else {
		return true;
	    }
	}
	catch (Exception e) {
	    System.out.println("ScheduleD:deleteDetailRecords:Error:"+e);
	    return false;
	}
    }
    
    private boolean deletePreHoldingInDetailRecords (String fid, String user_name) {
	try {
	    if (ejbdb == null) {
		ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	    }

	    String query = "DELETE FROM TAX_SCHEDULE_D_DETAIL WHERE USER_NAME='"+
		user_name+"' AND FID="+fid+" AND STATUS=3;";
	    if(ejbdb.delete(query)<0) {
		return false;
	    }
	    else {
		return true;
	    }
	}
	catch (Exception e) {
	    System.out.println("ScheduleD:deleteDetailRecords:Error:"+e);
	    return false;
	}
    }
    
    private StringBuffer viewPreYearHoldingRecords(String user_name, int user_level, String fid, String year, String broker){

	if(user_name == null || fid == null || year == null || broker == null || user_level <1) {
	    return null;
	}

	Vector vv = null;
	try {
	    if (ejbdb == null) {
		ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	    }
	    vv = ejbdb.selectSingleFieldScheduleDData(Integer.parseInt(fid), user_name, "PRE_HOLD");
	}
	catch (Exception e) {
	    System.out.println("ScheduleD:viewPreYearHoldingRecords:Error:Ejbdb"+e);
	    return null;
	}

	if(vv == null || vv.isEmpty()) {
	    return null;
	}

	StringBuffer sbf = new StringBuffer();	
	sbf.append("<TABLE cellSpacing='0' cellPadding='2' style='font-size: 8pt' border=1 width=90%>");
	sbf.append("<TR>");
	sbf.append("<TD align=center colspan=7>");
	sbf.append("<BR><H3>PRE-YEAR HOLDING records</H3>");
	sbf.append("</TD></TR>");
	sbf.append("<TR>");
	sbf.append("<TD align=center colspan=7><B>Broker</B> ["+getBrokerName(broker)+"] <B>Year</B> ["+year+"]</TD>");
	sbf.append("</TR>");
	sbf.append("<TR>");
	sbf.append("<TD>&nbsp;</TD>");
	sbf.append("<TD align=center><B>LONG/SHORT</B></TD><TD align=center><B>COST</B></TD>");
	sbf.append("<TD align=center><B>TICK</B></TD><TD align=center><B>SHARES</B></TD>");
	sbf.append("<TD align=center><B>PRICE</B></TD><TD align=center><B>DATE</B></TD>");
	sbf.append("</TR>");

	Enumeration enum1 = vv.elements();
	Enumeration enum2 = null;
	Vector v = null;
	int n=0;
	while(enum1.hasMoreElements()) {
	    n++;
	    v = (Vector)enum1.nextElement();
	    enum2 = v.elements();
	    while(enum2.hasMoreElements()) {
		sbf.append("<TR>");
		sbf.append("<TD align=center>"+n+"</TD>");
		sbf.append("<TD align=center>"+enum2.nextElement()+"</TD>");
		sbf.append("<TD align=center>"+enum2.nextElement()+"</TD>");
		sbf.append("<TD align=center>"+enum2.nextElement()+"</TD>");
		sbf.append("<TD align=center>"+enum2.nextElement()+"</TD>");
		sbf.append("<TD align=center>"+enum2.nextElement()+"</TD>");
		sbf.append("<TD align=center>"+enum2.nextElement()+"</TD>");
		sbf.append("</TR>");
	    }
	}
	sbf.append("</TABLE>");
	return sbf;
    }

    private StringBuffer confirmPreYearHoldingMessage (String broker, String base_year) {
	StringBuffer sbf = new StringBuffer();
	sbf.append("<H2>[PRE-YEAR HODLING] of ["+getBrokerName(broker)+"] ACCOUNT</H2>");
	sbf.append("<TABLE border=0  cellSpacing=0 cellPadding=2 width=90%>");
	sbf.append("<TR><TD><img src=/images/space.gif width=50>Any Long or Short positions CARRIED OVER to year ["+base_year+"]");
	sbf.append(" ["+getBrokerName(broker)+"] account,");
	sbf.append(" you must add it into [PRE-YEAR HOLDING] records. You only need to do once for your ");
	sbf.append("["+getBrokerName(broker)+"] account.</B></TD></TR>");
	sbf.append("<TR><TD><BR><BR>Example :<BR>James bought 100 shares QQQ in [1990] in his [ABC] account");
	sbf.append(" and sold 100 shares in [2000].");
	sbf.append(" When James files 2000 Schedule-D, year 2000's Form-1099 data only shows that James sold 100 shares QQQ.");
	sbf.append(" Since 2000 was James first time using 3WCenter.com Schedule-D generator, James has to");
	sbf.append(" menuly add the 100 shares QQQ information into 2000 [PRE-YEAR HOLDING] section.");
	sbf.append("<BR><BR><I>* If you need help, pleae to to TAX/Forum</I></TD></TR>");
	sbf.append("</TABLE>");
	return sbf;
    }
  
    private StringBuffer addPreYearHoldingRecords(HttpServletRequest request, String call_path, String mid, String aid,
						  String user_name, int user_level, String year, String broker, 
						  String status, String fid, String vid) {
	String error = null;
	String submit = request.getParameter("submit_h");
	HttpSession  session = request.getSession(true);

	if(submit != null && submit.equals("Delete")) {
	    session.setAttribute("PreHoldingRecords", null);
	}

	if(submit != null && submit.equals("Delete All")) {
	    session.setAttribute("PreHoldingRecords", null);
	    error = saveDeletePreYearHolding(user_name, fid, null);
	}

	Vector vv = (Vector)session.getAttribute("PreHoldingRecords");
	if(vv == null) {
	    try {
		if (ejbdb == null) {
		    ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
		}

		vv = ejbdb.selectSingleFieldScheduleDData(Integer.parseInt(fid), user_name, "PRE_HOLD");
		if(vv == null || vv.isEmpty()) {
		    vv = new Vector();
		}
		else {
		    session.setAttribute("PreHoldingRecords", vv);
		}
	    }
	    catch (Exception e) {
		System.out.println("ScheduleDUpdate:addPreYearHoldingRecords:Error:Ejbdb"+e);
		return null;
	    }
	}

	Hashtable rshs = null;
	Vector ve      = null;
	
	String bs    = null;
	String tick  = null;
	String cost  = null;
	String share = null;
	String price = null;

	if(submit != null && submit.equals("Add")) {
	    rshs  = new Hashtable();

	    for(int i=1; i<=10; i++) {
		bs    = request.getParameter("bs_"+i);
		tick  = request.getParameter("tick_"+i);
		cost  = request.getParameter("cost_"+i);
		share = request.getParameter("share_"+i);
		price = request.getParameter("price_"+i);

		if((bs == null || bs.equals("-1")) && 
		   (tick == null || tick.length()==0) && 
		   (cost == null || cost.length()==0) &&
		   (share == null || share.length()==0) &&
		   (price == null || price.length()==0)) {
		    continue;
		}

		ve = new Vector();
		ve.add(bs);
		ve.add(cost);
		ve.add(tick.toUpperCase());
		ve.add(share);
		ve.add(price);
		ve.add((Integer.parseInt(year)-1)+"-12-31");
		rshs.put(""+i, ve);
	    }

	    for(int i=1; i<=10; i++) {
		bs    = request.getParameter("bs_"+i);
		cost  = request.getParameter("cost_"+i);
		tick  = request.getParameter("tick_"+i);
		share = request.getParameter("share_"+i);
		price = request.getParameter("price_"+i);


		if((bs == null || bs.equals("-1")) && 
		   (tick == null || tick.length()==0) && 
		   (cost == null || cost.length()==0) &&
		   (share == null || share.length()==0) &&
		   (price == null || price.length()==0)) {
		    continue;
		}

		if(bs == null || bs.equals("-1")) {
		    error = "Error found at row ["+i+"]. Please select [LONG/SHORT].";
		    break;
		}

		if(tick == null || tick.length()==0) {
		    error = "Error found at row ["+i+"]. Please enter [TICK].";
		    break;
		}

		if(cost == null || cost.length()==0) {
		    error = "Error found at row ["+i+"]. Please enter [COST].";
		    break;
		}
		else {
		    if(!MyUserInputCheck.checkMoney(cost)) {
			error = "Error found at row ["+i+"] column [COST].";
			break;
		    }
		}
		
		if(share == null || share.length()==0) {
		    error = "Error found at row ["+i+"]. Please enter [SHARES].";
		    break;
		}
		else {
		    if(!MyUserInputCheck.isNumber(share)) {
			error = "Error found at row ["+i+"] column [SHARES] (Numbers Only).";
			break;
		    }
		}
		
		if(price == null || price.length()==0) {
		    error = "Error found at row ["+i+"]. Please enter [PRICE].";
		    break;
		}
		else {
		    if(!MyUserInputCheck.checkMoney(price)) {
			error = "Error found at row ["+i+"] column [PRICE].";
			break;
		    }
		}
	    }

	    if(error == null) {
		Enumeration enum = rshs.keys();
		int j=0;
		String key = null;
		while(enum.hasMoreElements()) {
		    key = (String)enum.nextElement();
		    vv.add(rshs.get(key));
		    j++;
		}
		if(j>0) {
		    rshs = null;
		    session.setAttribute("PreHoldingRecords",vv);
		}
		else {
		    error = "No Data.";
		}
	    }
	}

	StringBuffer sbf = new StringBuffer();

	if(vv != null && !vv.isEmpty()) {
	    try {
		String save_error = null;
		if(submit != null && submit.equals("Save")) {
		    save_error = saveDeletePreYearHolding(user_name, fid, vv);
		    if(save_error == null) {
			session.setAttribute("PreHoldingRecords", null);

			sbf.append("<BR><BR>");
			sbf.append("<TABLE align=center>");
			sbf.append("<TR>");
			sbf.append("<TD><B> Do you have any more PRE-YEAR HOLDING need to be added?</B>");
			sbf.append("</TD>");
			sbf.append("</TR>");
			sbf.append("</TABLE>");

			sbf.append("<BR><BR><TABLE align=center>");
			sbf.append("<TR>");
			sbf.append("<TD>");
			sbf.append("<FORM method=post action="+call_path+">");
			sbf.append("<input type=submit name=submit_h value='Yes' style='font-size: 8pt'>");
			sbf.append("<input type=hidden name=stid value="+status+">");
			sbf.append("<input type=hidden name=vid value="+vid+">");
			sbf.append("<input type=hidden name=fid value="+fid+">");
			sbf.append("<input type=hidden name=yid value="+year+">");
			sbf.append("<input type=hidden name=bid value="+broker+">");
			sbf.append("<input type=hidden name=mid value="+mid+">");
			sbf.append("<input type=hidden name=aid value="+aid+">");
			sbf.append("<input type=hidden name=caid value=Yes>");
			sbf.append("</FORM>");
			sbf.append("</TD>");
			sbf.append("<TD>");
			sbf.append("<FORM method=post action="+call_path+">");
			sbf.append("<input type=submit name=submit_h value='No' style='font-size: 8pt'>");
			sbf.append("<input type=hidden name=stid value="+status+">");
			sbf.append("<input type=hidden name=vid value="+vid+">");
			sbf.append("<input type=hidden name=fid value="+fid+">");
			sbf.append("<input type=hidden name=yid value="+year+">");
			sbf.append("<input type=hidden name=bid value="+broker+">");
			sbf.append("<input type=hidden name=mid value="+mid+">");
			sbf.append("<input type=hidden name=aid value="+aid+">");
			sbf.append("<input type=hidden name=caid value=No>");
			sbf.append("</FORM>");
			sbf.append("</TD>");
			sbf.append("</TR>");
			sbf.append("</TABLE>");
			return sbf;
		    }
		    else {
			submit = "View/Save/Delete";
		    }
		}

		sbf.append("<TABLE cellSpacing='0' cellPadding='2' style='font-size: 8pt' border=1 width=90%>");
		sbf.append("<TR>");
		sbf.append("<TD align=center colspan=7>");
		sbf.append("<BR><H3>Added PRE-YEAR HOLDING</H3>");
		sbf.append("</TD></TR>");
		sbf.append("<TR>");
		sbf.append("<TD align=center colspan=7><B>Broker</B> ["+getBrokerName(broker)+"] <B>Year</B> ["+year+"]</TD>");
		sbf.append("</TR>");

		if(save_error != null) {
		    sbf.append("<TR>");
		    sbf.append("<TD align=center colspan=7><img src=/images/star.gif><I>"+save_error+"</I></TD>");
		    sbf.append("</TR>");
		}

		sbf.append("<TR>");
		sbf.append("<TD>&nbsp;</TD>");
		sbf.append("<TD align=center><B>LONG/SHORT</B></TD><TD align=center><B>COST</B></TD>");
		sbf.append("<TD align=center><B>TICK</B></TD><TD align=center><B>SHARES</B></TD>");
		sbf.append("<TD align=center><B>PRICE</B></TD><TD align=center><B>DATE</B></TD>");
		sbf.append("</TR>");

		Enumeration enum1 = vv.elements();
		Enumeration enum2 = null;
		Vector v = null;
		int n=0;
		while(enum1.hasMoreElements()) {
		    n++;
		    v = (Vector)enum1.nextElement();
		    enum2 = v.elements();
		    while(enum2.hasMoreElements()) {
			sbf.append("<TR>");
			sbf.append("<TD align=center>"+n+"</TD>");
			sbf.append("<TD align=center>"+enum2.nextElement()+"</TD>");
			sbf.append("<TD align=center>"+enum2.nextElement()+"</TD>");
			sbf.append("<TD align=center>"+enum2.nextElement()+"</TD>");
			sbf.append("<TD align=center>"+enum2.nextElement()+"</TD>");
			sbf.append("<TD align=center>"+enum2.nextElement()+"</TD>");
			sbf.append("<TD align=center>"+enum2.nextElement()+"</TD>");
			sbf.append("</TR>");
		    }
		}
		sbf.append("</TABLE>");

		sbf.append("<FORM method=post action="+call_path+">");
		sbf.append("<TABLE>");

		if(submit != null && submit.equals("View/Save/Delete")) {
		    sbf.append("<TR>");
		    sbf.append("<TD align=center>");
		    sbf.append("<input type=submit name=submit_h value='Save' style='font-size: 8pt'>");
		    sbf.append("</TD>");
		    sbf.append("<TD align=center>");
		    sbf.append("<input type=submit name=submit_h value='Delete' style='font-size: 8pt'>");
		    sbf.append("</TD>");
		    sbf.append("<TD align=center>");
		    sbf.append("<input type=submit name=submit_h value='Delete All' style='font-size: 8pt'>");
		    sbf.append("</TD>");
		    sbf.append("<TD align=center>");
		    sbf.append("<input type=submit name=submit_h value='Add More' style='font-size: 8pt'>");
		    sbf.append("</TD></TR>");
		}
		else {
		    sbf.append("<TR>");
		    sbf.append("<TD align=center>");
		    sbf.append("<input type=submit name=submit_h value='View/Save/Delete' style='font-size: 8pt'>");
		    sbf.append("</TD>");
		    sbf.append("</TR>");
		}

		sbf.append("</TABLE>");
		sbf.append("<input type=hidden name=stid value="+status+">");
		sbf.append("<input type=hidden name=vid value="+vid+">");
		sbf.append("<input type=hidden name=fid value="+fid+">");
		sbf.append("<input type=hidden name=yid value="+year+">");
		sbf.append("<input type=hidden name=bid value="+broker+">");
		sbf.append("<input type=hidden name=mid value="+mid+">");
		sbf.append("<input type=hidden name=aid value="+aid+">");
		sbf.append("<input type=hidden name=caid value=Yes>");
		sbf.append("</FORM>");

		if(submit != null && submit.equals("View/Save/Delete")) {
		    return sbf;
		}
	    }
	    catch(Exception e) {
		System.out.println("ScheduleDUpdate:addPreYearHoldingRecords:Error:301:"+e);
	    }
	}

	try {
	    sbf.append("<FORM method=post action="+call_path+">");
	    sbf.append("<TABLE cellSpacing='0' cellPadding='2' style='font-size: 8pt' border=1 width=90%>");
	    sbf.append("<TR>");
	    sbf.append("<TD align=center colspan=7>");
	    sbf.append("<BR><H3>Adding [PRE-YEAR HOLDING] record</H3>");
	    sbf.append("</TD></TR>");
	    sbf.append("<TR>");
	    sbf.append("<TD align=center colspan=7><B>Broker</B> ["+getBrokerName(broker)+"] <B>Year</B> ["+year+"]</TD>");
	    sbf.append("</TR>");
	    sbf.append("<TR>");
	    sbf.append("<TD align=center colspan=7>");
	    sbf.append("<input type=submit value='Add' name=submit_h style='font-size: 8pt'>"); 
	    sbf.append("<input type=reset value='Reset' name=submit_h style='font-size: 8pt'>"); 
	    sbf.append("</TD></TR>");

	    if(error != null && submit != null && submit.equals("Add")) {
		sbf.append("<TR>");
		sbf.append("<TD align=center colspan=7>");
		sbf.append("<img src=/images/star.gif><I>"+error+"</I>");
		sbf.append("</TR>");
	    }

	    sbf.append("<TR><TD>&nbsp;</TD>");
	    sbf.append("<TD align=center><B>LONG/SHORT</B></TD><TD align=center><B>COST</B></TD>");
	    sbf.append("<TD align=center><B>TICK</B></TD><TD align=center><B>SHARES</B></TD>");
	    sbf.append("<TD align=center><B>PRICE</B></TD><TD align=center><B>DATE</B></TD>");
	    sbf.append("</TR>");
	
	    for(int i=1; i<=10; i++) { 
		bs    = "-1";
		tick  = "";
		cost  = "";
		share = "";
		price = "";
   
		if(rshs != null) {
		    Vector v = (Vector)rshs.get(""+i);
		    if(v != null && !v.isEmpty()) {
			//System.out.println(v);
			bs    = (String)v.elementAt(0);
			cost  = (String)v.elementAt(1);
			tick  = (String)v.elementAt(2);
			share = (String)v.elementAt(3);
			price = (String)v.elementAt(4);
		    }
		}

		sbf.append("<TR>");
		sbf.append("<TD align=center>"+i+"</TD>");
		sbf.append("<TD align=center><select name=bs_"+i+">");

		if(bs.equals("B")) {
		    sbf.append("<option value=-1>-------</option>");
		    sbf.append("<option selected value=B>Long(B)</option>");
		    sbf.append("<option value=S>Short(S)</option>");
		}
		else if(bs.equals("S")) {
		    sbf.append("<option value=-1>-------</option>");
		    sbf.append("<option value=B>Long(B)</option>");
		    sbf.append("<option selected value=S>Short(S)</option>");
		}
		else {
		    sbf.append("<option selected value=-1>-------</option>");
		    sbf.append("<option value=B>Long(B)</option>");
		    sbf.append("<option value=S>Short(S)</option>");
		}
		sbf.append("</select></TD>");
		sbf.append("<TD align=center><input type=text name=cost_"+i+"  value='"+cost+"' size=10 maxLenght=10></TD>");
		sbf.append("<TD align=center><input type=text name=tick_"+i+"  value='"+tick+"' size=10 maxLenght=10></TD>");
		sbf.append("<TD align=center><input type=text name=share_"+i+" Value='"+share+"' size=10 maxLenght=10></TD>");
		sbf.append("<TD align=center><input type=text name=price_"+i+" value='"+price+"' size=10 maxLenght=10></TD>");
		sbf.append("<TD align=center>"+(Integer.parseInt(year)-1)+"-12-31</TD>");
		sbf.append("</TR>");
	    }

	    sbf.append("<TR>");
	    sbf.append("<TD align=center colspan=7>");
	    sbf.append("<input type=submit value='Add' name=submit_h style='font-size: 8pt'>"); 
	    sbf.append("<input type=reset value='Reset' name=submit_h style='font-size: 8pt'>"); 
	    sbf.append("</TD></TR>");
	    sbf.append("</TABLE>");
	    sbf.append("<input type=hidden name=stid value="+status+">");
	    sbf.append("<input type=hidden name=vid value="+vid+">");
	    sbf.append("<input type=hidden name=fid value="+fid+">");
	    sbf.append("<input type=hidden name=yid value="+year+">");
	    sbf.append("<input type=hidden name=bid value="+broker+">");
	    sbf.append("<input type=hidden name=mid value="+mid+">");
	    sbf.append("<input type=hidden name=aid value="+aid+">");
	    sbf.append("<input type=hidden name=caid value=Yes>");
	    sbf.append("</FORM>");
	}
	catch (Exception e) {
	    System.out.println("ScheduleDUpdate:addPreYearHoldingRecords:Error:401:"+e);
	}
	return sbf;
    }

    private StringBuffer viewEditPreYearHoldingRecords(HttpServletRequest request, String call_path, String mid, String aid,
						       String user_name, int user_level, String yid, String bid, 
						       String stid, String fid, String vid) {
	StringBuffer vsbf = null;
	vsbf = viewPreYearHoldingRecords(user_name, user_level, fid, yid, bid);
	StringBuffer sbf = new StringBuffer();
	if(vsbf == null) {
	    sbf.append("<TABLE cellSpacing='0' cellPadding='2' style='font-size: 10pt' border=1 width=90%>");
	    sbf.append("<TR>");
	    sbf.append("<TD align=center colspan=7>");
	    sbf.append("<BR><H3>PRE-YEAR HOLDING RECORDS</H3>");
	    sbf.append("</TD></TR>");
	    sbf.append("<TR>");
	    sbf.append("<TD align=center colspan=6><B>Broker</B> ["+getBrokerName(bid)+"] <B>Year</B> ["+yid+"]</TD>");
	    sbf.append("</TR>");
	    
	    sbf.append("<TR>");
	    sbf.append("<TD align=center><B>LONG/SHORT</B></TD><TD align=center><B>COST</B></TD>");
	    sbf.append("<TD align=center><B>TICK</B></TD><TD align=center><B>SHARES</B></TD>");
	    sbf.append("<TD align=center><B>PRICE</B></TD><TD align=center><B>DATE</B></TD>");
	    sbf.append("</TR>");
	    sbf.append("</TABLE>");
	}
	else {
	    sbf.append(vsbf);
	}

	sbf.append("<FORM method=post action="+call_path+">");
	sbf.append("<TABLE>");
	sbf.append("<TR>");
	sbf.append("<TD align=center>");
	if(vsbf==null) {
	    sbf.append("<input type=submit name=B value='Add' style='font-size: 8pt'>");
	}
	else {
	    sbf.append("<input type=submit name=B value='Edit/Add' style='font-size: 8pt'>");

	}
	sbf.append("</TD>");
	sbf.append("</TR>");
	sbf.append("</TABLE>");
	sbf.append("<input type=hidden name=stid value="+stid+">");
	sbf.append("<input type=hidden name=vid value="+vid+">");
	sbf.append("<input type=hidden name=fid value="+fid+">");
	sbf.append("<input type=hidden name=yid value="+yid+">");
	sbf.append("<input type=hidden name=bid value="+bid+">");
	sbf.append("<input type=hidden name=mid value="+mid+">");
	sbf.append("<input type=hidden name=aid value="+aid+">");
	sbf.append("<input type=hidden name=caid value=Edit>");
	sbf.append("</FORM>");

	return sbf;
    }

    private String saveDeletePreYearHolding(String user_name, String fid, Vector vv) {
	try {
	    if (ejbdb == null) {
		ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	    }

	    if(deletePreHoldingInDetailRecords (fid, user_name)) {
		if(!ejbdb.updateScheduleD1099PreHolding(user_name, fid, vv)) {
		    return "Save data error. Please try again.";
		}
	    }
	    else {
		return "Save data error. Please try again.";
	    }
	}
	catch (Exception e) {
	    System.out.println("ScheduleDUpdate:saveDeletePreYearHolding:Error:Ejbdb"+e);
	    return "Save data error.";
	}

	return null;
    }

    private String generateDetailRecords (String user_name, String year, String broker, String fid, String status) {
	if(user_name == null || year == null || broker == null || fid == null || status == null) {
	    return "Data not found.";
	}
	
	try {
	    if (ejbdb == null) {
		ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	    }
	}
	catch (Exception e) {
	    System.out.println("ScheduleDUpdate:generateDetailRecords:Error:Ejbdb"+e);
	    return "System error.";
	}

	Vector vv  = null; 
	Vector v   = null;

	Vector vvn = new Vector(); 
	Vector vn  = null;

	String bs    = null;
	String cost  = null;
	String tick  = null;
	String share = null;
	String price = null;
	String date  = null;

	try {
	    vv = ejbdb.selectSingleFieldScheduleDData(Integer.parseInt(fid), user_name, "TRA_DATA");
	    if(vv != null && !vv.isEmpty()) {
		Enumeration enum1 = vv.elements();
		Enumeration enum2 = null;
		while(enum1.hasMoreElements()) {
		    v = (Vector)enum1.nextElement();
		    v.trimToSize();
		    if(v.size() != 6) {
			System.out.println("ScheduleDUpdate:generateDetailRecords:Error:size<>6");
			return "Processing Data error."+v.toString();
		    }
		    enum2 = v.elements();
		
		    while(enum2.hasMoreElements()) {
			bs    = (String)enum2.nextElement();
			cost  = (String)enum2.nextElement();
			tick  = (String)enum2.nextElement();
			share = (String)enum2.nextElement();
			price = (String)enum2.nextElement();
			date  = (String)enum2.nextElement();
		    }

		    vn = new Vector();
		    vn.add(bs);    //bs
		    vn.add(cost);  //cost
		    vn.add(tick);  //tick
		    vn.add(share); //share
		    vn.add(price); //price
		    vn.add(MyDateFormat.format1(date, 1)); //date
		    System.out.println(vn);
		    vvn.add(vn);
		}
		
		enum1 = null; 
		enum2 = null;
		vv    = null;
		v     = null;
	    }
	}
	catch (Exception e) {
	    System.out.println("ScheduleDUpdate:generateDetailRecords:Error:100:"+e);
	    return "System error.";
	}

	return (insertDetailRecords(user_name, year, broker, fid, status, vvn));
    }

    private String addPreYearIntoDetail (String user_name, String year, String broker, String fid, String status) {
	if(user_name == null || year == null || broker == null || fid == null || status == null) {
	    System.out.println("ScheduleDUpdate:addPreYearIntoDetail:101");
	    return "Data not found.";
	}

	try {
	    if (ejbdb == null) {
		ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	    }

	    Vector vvh = ejbdb.selectSingleFieldScheduleDData(Integer.parseInt(fid), user_name, "PRE_HOLD");
	    if(vvh != null && !vvh.isEmpty()) {
		return insertDetailRecords(user_name, year, broker, fid, status, vvh);
	    }
	    return null;
	}
	catch (Exception e) {
	    System.out.println("ScheduleDUpdate:addPreYearIntoDetail:102"+e);
	    return "System error.";
	}
    }
    
    private String insertDetailRecords (String user_name, String year, String broker, String fid, String status, Vector vv) {
	if(user_name == null || year == null || broker == null || fid == null || status == null) {
	    return "Data not found.";
	}

	try {
	    if (ejbdb == null) {
		ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	    }
	    if(deleteDetailRecords (fid, user_name, year, broker, status)) {
		if(0 > ejbdb.insertScheduleDDetailRecords(Integer.parseInt(fid), user_name, Integer.parseInt(year), 
							  Integer.parseInt(broker), Integer.parseInt(status), vv)) {
		    System.out.println(vv);
		    return "Save data error[102]";
		}
	    }
	    else {
		return "System error[103]";
	    }
	}
	catch (Exception e) {
	    System.out.println("ScheduleD:insertDetailRecords:Error:100:"+e);
	    return "System error[401]";
	}
	return null;
    }

    private boolean saveThisYearHoldingRecords (String user_name, String year, String broker, String fid) {
	if(user_name == null || year == null || broker == null || fid == null) {
	    return false;
	}

	try {
	    if (ejbdb == null) {
		ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	    }
	    if(ejbdb.deleteThisYearHoldingRecords(fid, user_name, year, broker)) {
		int order = 0;  //[0: DATE] [1: BS] [2: TICK]
		Vector vv = ejbdb.selectScheduleDDetailRecordVector(fid, order); 
		Vector vr = getHoldingRecordVector(fid, user_name, year, broker, vv);
		return ejbdb.saveThisYearHoldingRecords(fid, user_name,  year, broker, vr);
	    }
	}
	catch (Exception e) {
	    System.out.println("ScheduleDUpdate:saveThisYearHoldingRecords:Error:"+e);
	    return false;
	}
	return false;
    }
}









